import React, { useState } from 'react';
import {
  Form,
  Select,
  Tooltip,
  SelectBox,
  Modal,
} from 'choerodon-ui/pro';
import { axios } from '@choerodon/master';
import { observer } from 'mobx-react-lite';
import { NewTips } from '@choerodon/components';
import { initValueIdDataSet } from '@/routes/app-pipeline/routes/pipeline-manage/components/PipelineCreate/components/AddCDTask/stores/addCDTaskDataSet';
import { mapping, deployConfigDataSet, appNameChartDataSet } from '../../stores/deployChartDataSet';
import YamlEditor from '@/components/yamlEditor';
import DeployConfig from '@/components/deploy-config-form';
import DeployChart from '@/routes/app-pipeline/routes/pipeline-manage/components/PipelineCreate/components/AddCDTask/components/deploy-chart';

import './index.less';

const { Option } = Select;

const Index = observer(({
  ds,
  DeployChartDataSet,
  ADDCDTaskUseStore,
  appServiceId,
  appServiceName,
  projectId,
  level,
  type,
}: any) => {
  const [valueIdValues, setValueIdValues] = useState('');

  const optionRenderValueId: any = ({ value, text, record }: any) => rendererValueId({ text });

  const handleClickCreateValue = (e: any) => {
    e.preventDefault();
    e.stopPropagation();
    Modal.open({
      key: Modal.key(),
      drawer: true,
      style: {
        width: '740px',
      },
      className: 'c7ncd-pipeline-create-value',
      children: (
        <DeployConfig
          envId={ds.current.get('envId')}
          appServiceId={appServiceId}
          appServiceName={appServiceName}
          //   @ts-ignore
          refresh={({ valueId, value }: any): any => {
            ADDCDTaskUseStore.setValueIdRandom(Math.random());
            DeployChartDataSet.current.set('valueId', valueId);
            DeployChartDataSet.current.set(mapping().deployConfig.name, valueId);
            DeployChartDataSet.current.set(mapping().value.name, value);
            initValueIdDataSet(
              deployConfigDataSet,
              appServiceId,
              ds.current.get('envId'),
              ADDCDTaskUseStore.getValueIdRandom,
            );
            setValueIdValues(value);
          }}
          appSelectDisabled
        />
      ),
      title: '创建部署配置',
      okText: '创建',
    });
  };

  const rendererValueId: any = ({ value, text, record }: any) => (text === '创建部署配置' ? (
    <a
      style={{
        width: 'calc(100% + 0.24rem)',
        display: 'inline-block',
        position: 'relative',
        right: '0.12rem',
      }}
      role="none"
      onClick={(e) => handleClickCreateValue(e)}
    >
      <span style={{ marginLeft: '0.12rem' }}>{text}</span>
    </a>
  ) : (
    text
  ));

  const renderer = ({ record, text }: any) => (
    <span>
      {text && (
        <i
          style={{
            display: 'inline-block',
            marginRight: 3,
            width: '0.08rem',
            height: '0.08rem',
            borderRadius: '50%',
            backgroundColor: record?.get('connected') ? 'rgb(0, 191, 165)' : '#ff9915',
          }}
        />
      )}
      {text}
    </span>
  );

  /**
   * 修改配置信息事件
   */
  const handleChangeValueIdValues = (data: any) => {
    const { value, valueIdList, valueId } = data;
    let tempValues = value || valueIdValues;
    const item = (valueIdList || ADDCDTaskUseStore.getValueIdList).find(
      (i: any) => String(i.id) === String(valueId || ds.current.get('valueId')),
    );
    Modal.open({
      key: Modal.key(),
      drawer: true,
      title: `修改部署配置"${item?.name || ''}"的配置信息`,
      children: (
        <div
          style={{
            maxHeight: 500,
          }}
        >
          <YamlEditor
            colSpan={3}
            newLine
            readOnly={false}
            className="addcdTask-yamleditor"
            onValueChange={(data1: any) => {
              tempValues = data1;
            }}
            value={tempValues}
          />
        </div>
      ),
      style: {
        width: '740px',
      },
      okText: '修改',
      onOk: async () => {
        await axios.post(`/devops/v1/projects/${projectId}/deploy_value`, {
          ...(valueIdList || ADDCDTaskUseStore.getValueIdList).find(
            (i: any) => String(i.id) === String(valueId || ds.current.get('valueId')),
          ),
          value: tempValues,
        });
        ADDCDTaskUseStore.setValueIdRandom(Math.random());
        setValueIdValues(tempValues);
        if (data) {
          const item2 = DeployChartDataSet.current.getField(mapping().deployConfig.name).options.records.find((item1: any) => item1.get('id') === data.valueId);
          if (item2) {
            item2.set('value', tempValues);
          }
          DeployChartDataSet.current.set(mapping().deployConfig.name, data.valueId);
          DeployChartDataSet.current.set(mapping().value.name, tempValues);
        }
      },
      onCancel: () => {},
    });
  };

  const optionRenderer = ({ record, text, value }: any) => (
    <Tooltip title={!record?.get('connected') && '未连接'}>
      {renderer({ record, text, value })}
    </Tooltip>
  );
  return (
    <>
      <Form columns={2} dataSet={ds}>
        <Select
          colSpan={1}
          name="envId"
          onChange={() => {
            DeployChartDataSet?.current?.set(mapping().deployConfig.name, undefined);
            DeployChartDataSet?.current?.set(mapping().value.name, undefined);
            DeployChartDataSet.current.set(mapping().appName.name, undefined);
            DeployChartDataSet.current.set(mapping().appId.name, undefined);
            DeployChartDataSet.current.set(mapping().appCode.name, undefined);
            deployConfigDataSet.setQueryParameter('envId', ds.current.get('envId'));
            deployConfigDataSet.setQueryParameter('appServiceId', appServiceId);
            deployConfigDataSet.query();

            appNameChartDataSet.setQueryParameter('envId', ds.current.get('envId'));
            appNameChartDataSet.setQueryParameter('appServiceId', appServiceId);
            appNameChartDataSet.query();
          }}
          optionRenderer={optionRenderer}
                  // renderer={renderer}
          onOption={({ record }) => ({
            disabled: !record?.get('connected'),
          })}
        />
        <div
          className="addcdTask-whetherBlock addcdTask-triggersTasks"
          style={{
            position: 'relative',
          }}
            // @ts-ignore
          colSpan={3}
        >
          <SelectBox name="skipCheckPermission">
            <Option value>是</Option>
            <Option value={false}>否</Option>
          </SelectBox>
          <NewTips
            helpText="此处仅项目所有者可以设置；默认为是，即触发用户在没有该部署任务的环境权限时，将会直接使用管理员账户触发部署；若选择为否，触发成员在没有环境权限时，将会直接跳过此部署任务。"
            style={{
              position: 'absolute',
              top: '7px',
              left: '195px',
            }}
          />
        </div>
        <SelectBox
          colSpan={3}
          name="deployType"
          onChange={(value) => {
          // 待修改
            //   DeployGroupDataSet.current.set(deployGroupMapping().appName.name, undefined);
            //   DeployGroupDataSet.current.set(deployGroupMapping().appCode.name, undefined);
            DeployChartDataSet.current.set(mapping().appCode.name, undefined);
            DeployChartDataSet.current.set(mapping().appName.name, undefined);
          }}
        />
      </Form>
      <div className="addcdTask-divided" />
      <DeployChart
        envId={ds.current.get('envId')}
        deployWay={ds.current.get('deployType')}
        dataSet={DeployChartDataSet}
        optionRenderValueId={optionRenderValueId}
        rendererValueId={rendererValueId}
        appServiceId={appServiceId}
        handleChangeValueIdValues={handleChangeValueIdValues}
        disabled={(level !== 'project' || window.location.href.includes('project-pipeline-template')) && !type?.includes('cd_')}
      />
    </>
  );
});

export default Index;
